package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userinfo")
    public String userinfo(@RequestParam(value = "token") String token) {
        String s = redisTemplate.opsForValue().get(token);

        return s;

    }

    @GetMapping("/login.html")
    public String toLoginPage(@RequestParam(value = "redirect_url") String redirect_url, Model model,@CookieValue(value = "sso_token", required = false) String sso_token){
        if (!StringUtils.isEmpty(sso_token)) {
            return "redirect:" + redirect_url + "?token=" + sso_token;
        }
        model.addAttribute("redirectUrl",redirect_url);
        return "login";
    }


    @PostMapping("/doLogin")
    public String login(String username,String password,String redirectUrl,HttpServletResponse resp){

        if(username!=null && password !=null && redirectUrl !=null){
            String uuid = UUID.randomUUID().toString().replace("-","");
            redisTemplate.opsForValue().set(uuid,username);
            Cookie cookie = new Cookie("sso_token",uuid);
            resp.addCookie(cookie);
            return "redirect:"+redirectUrl+"?token="+uuid;
        }
        return "login";
    }
}
